<template>
  <span v-if="address">
    <i class="bi bi-geo-alt"></i>当前位置:
    <strong>{{ address }}</strong>
  </span>
  <span v-else>当前位置:正在定位中...</span>
</template>

<script>
export default {
  data() {
    return {
      address: '',
    }
  },
  created() {
    let _this = this
    let sessionLocal = window.sessionStorage.getItem('address')
    if (sessionLocal) {
      _this.address = sessionLocal
    } else {
      _this.getLocation()
    }
  },
  methods: {
    getLocation() {
      let _this = this
      let geolocation = new BMap.Geolocation() // 创建百度地理位置实例，代替 navigator.geolocation
      geolocation.getCurrentPosition(function (e) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          // 百度 geolocation 的经纬度属性不同，此处是 point.lat 而不是 coords.latitude
          let point = new BMap.Point(e.point.lng, e.point.lat)
          let gc = new BMap.Geocoder()
          gc.getLocation(point, function (rs) {
            let addComp = rs.addressComponents // 返回的结果，大家可以先把rs打印出来看看是什么

            // let address = addComp.city + addComp.district + addComp.street // 拼接地址
            let address = addComp.city // 拼接地址
            _this.address = address
            window.sessionStorage.setItem('address', address) // 地址存入sessionStorage，再次进入页面就不需要再次请求位置了
            window.sessionStorage.setItem('cityName', addComp.city)
          })
        } else {
          console.log(this.getStatus())
        }
      })
    },
  },
}
</script>

<style lang="less" scoped></style>
